package com.example.dayu521.sg_oss.controller.msg;

import com.example.dayu521.sg_oss.controller.ProductTrade;
import com.example.dayu521.sg_oss.service.feign.PayServiceRpc;
import lombok.extern.slf4j.Slf4j;
import org.example.dayu521.OrRes;
import org.example.dayu521.OrderState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.function.Consumer;

@Component("delayCloseOrder")
@Slf4j
public class DelayCloseOrder implements Consumer<Long> {

    @Autowired
    private ProductTrade productTrade;

    @Autowired
    private PayServiceRpc payServiceRpc;

    @Override
    public void accept(Long aLong) {

        log.info(STR. "订单超时检查触发 \{ aLong }" );
        //拉取订单状态.因为定时任务是确定操作,需要确定支付状态
        OrRes<String> orRes = productTrade.decide_state_after_created(new PayServiceRpc.TradeStateParam(aLong.toString()));
        if (orRes.is_ok() && !OrderState.can_timeout(OrderState.valueOf(orRes.res()))) {//我们迟到了
            log.info("状态已经决定,无需修改订单状态");
        }else{
            orRes = productTrade.close_order(aLong, OrderState.Timeout, true);
            if (!OrderState.definite_state(orRes.res())) {
                throw new RuntimeException(STR. "订单状态无法确定 \{ orRes.res() },等待重试" );
            }
        }

        if(!payServiceRpc.clean_up_unreached_order(aLong.toString()).is_ok()){
            throw new RuntimeException(STR. "订单清理异常 \{ orRes.res() },等待重试" );
        }
        log.info(STR. "订单超时 \{ aLong } 检查触发,检查结束,订单完成 \{ orRes.res() }" );
    }
}
